package main

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"

	"gitee.com/law-api/routers"
	"gitee.com/law-api/stat"
)

//callbackResult return  result after callback
type callbackResult struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

func Failed() []byte {
	fail := &callbackResult{Code: -1, Msg: "失败"}
	responb, _ := json.Marshal(fail)
	return responb
}

func Succeed() []byte {
	fail := &callbackResult{Code: 0, Msg: "成功"}
	responb, _ := json.Marshal(fail)
	return responb
}

type uploadCB struct {
	static *stat.Counter
}

func newUploadCB() *uploadCB {
	//需要设置个定时计数器统计
	counter := stat.NewCounter()
	counter.Start()

	return &uploadCB{
		static: counter,
	}
}

//String show the main function of chain hanlder
func (uc *uploadCB) String() string {
	return "test"
}

func (uc *uploadCB) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		b, err := ioutil.ReadAll(r.Body)
		if err != nil {
			log.Printf("uploadCB: read request error, %v\n", err)
			w.Write(Failed())
			return
		}
		defer r.Body.Close()

		//解析请求
		req := new(routers.ChainDataResponse)
		if err = json.Unmarshal(b, req); err != nil {
			log.Printf("uploadCB: json parse error, %v\n", err)
			w.Write(Failed())
			return
		}

		uc.show(req.Data)

		w.Write(Succeed())
	} else {
		w.Write(Failed())
		log.Printf("unknown request: %v\n", r.Method)
	}
}

func (uc *uploadCB) show(chData []*routers.ChainData) {
	var succeed = 0
	for _, data := range chData {
		if data.Code == 0 {
			succeed++
			uc.static.PostCommitResult(true)
		} else {
			uc.static.PostCommitResult(false)
		}
		log.Printf("file_id: %v\n", data.FileID)
		log.Printf("tran_hash: %v\n", data.TxHash)
	}
	log.Printf("callback data! total filelist: %v, succeed filelist: %v\n", len(chData), succeed)

}

type chargeCB struct{}

func newChargeCB() *chargeCB {
	return &chargeCB{}
}

//String show the main function of chain hanlder
func (cc *chargeCB) String() string {
	return "test"
}

func (cc *chargeCB) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		b, err := ioutil.ReadAll(r.Body)
		if err != nil {
			log.Printf("chargeCB: read request error, %v\n", err)
			w.Write(Failed())
			return
		}
		defer r.Body.Close()

		//解析请求
		req := new(routers.ChargeStatusResponse)
		if err = json.Unmarshal(b, req); err != nil {
			log.Printf("chargeCB: json parse error, %v\n", err)
			w.Write(Failed())
			return
		}
		cc.show(req.Data)

		w.Write(Succeed())
	} else {
		w.Write(Failed())
		log.Printf("unknown request: %v\n", r.Method)
	}
}

func (cc *chargeCB) show(chStatus []*routers.ChargeStatus) {
	for _, sts := range chStatus {
		log.Printf("charge result, addr=%v, code:%v\n", sts.Addr, sts.Code)
	}
}
